package com.appspot.yttv.client;

import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.ui.SimplePanel;

/**
 * Simple panel to display TV static.
 * 
 * @author Alin Sinpalean
 */
public class StaticPanel extends SimplePanel {

	private static final int INTERVAL = 40;

	// We're visible initially.
	private boolean show = true;

	private Timer timer = new Timer() {
		@Override
		public void run() {
			tick();
			// Don't use a repeating timer. We want to free the CPU for 40ms 
			// every now and then to handle input events.
			schedule(INTERVAL);
		}
	};

	public StaticPanel(int width, int height) {
		setPixelSize(width, height);
		setStyleName("player static");
		timer.schedule(INTERVAL);
	}

	public void show() {
		show = true;
		DOM.setStyleAttribute(getElement(), "visibility", "visible");
		timer.cancel();
		timer.schedule(INTERVAL);
	}
	
	public void hide() {
		show = false;
		DOM.setStyleAttribute(getElement(), "visibility", "hidden");
		timer.cancel();
	}

	private void tick() {
		if (show) {
			// Move the background around while it's displayed.
			DOM.setStyleAttribute(getElement(), "backgroundPosition", 
					(int)(1024*Math.random()) + "px " + (int)(768*Math.random()) + "px");
		}
	}
}
